import { requestList } from './globalData'
/**
 * @author Dom
 * @description: 如无特殊注释，以下方法均可传递success、fail、complete者三个回调函数。
 * @description: 具体参数类型说明参照小程序官方文档、https://developers.weixin.qq.com/miniprogram/dev/api/
 */

/**
 * @author Dom
 * @param params, type: object
 * state: keys: url（必传）
 * @param data, type: object
 * state: 地址参数
 * @param isTabBarPage, type: boolean
 * state: 是否是tabBar页面
 * @return: undefined
 * @description: 调用wx.navigateTo进行重定向，并将参数进行格式化，拼接在地址后
 */
const navigateTo = (params, data, isTabBarPage) => {
    let pages = getCurrentPages();
    let pageLength = pages.length;
    let targetUrl = params.url.split('?')[0].slice(1);
    if(pages[pageLength - 1].route === targetUrl) return; //如果是当前页面, 则不进行跳转
    if (!params.url) {
        showToast({ title: 'url不能为空', duration: 1000 })
    } else {
        if (params.url.lastIndexOf('?') === params.url.length - 1) { //如果地址以"?"结尾则将"?"去掉
            params.url = params.url.slice(0, -1)
        }
        if (data) { //如果有数据, 则对参数进行处理
            let dataKeys = Object.keys(data);
            if (params.url.indexOf('?') !== -1) { //地址中已存在参数
                dataKeys.map(item => {
                    params.url += `&${item}=${data[item]}`
                })
            } else {
                dataKeys.map((item, index) => { //地址中未存在参数
                    if (index === 0) {
                        params.url += `?${item}=${data[item]}`
                    } else {
                        params.url += `&${item}=${data[item]}`
                    }
                })
            }
        }
        if (isTabBarPage) { //判断是否是tabBar页面
            wx.switchTab(params)
        } else {
            if(pages[pageLength - 2] && targetUrl === pages[pageLength - 2].route){
                navigateBack(params)
            } else {
                wx.navigateTo(params)
            }
        }
    }
};

const navigateBack = params => {
    params = Object.assign({}, { delta: 1 }, params); //默认返回一层
    wx.navigateBack(params)
};

/**
 * @author Dom
 * @param params, type: object
 * state: keys: url（必传）
 * @param data, type: object
 * state: 地址参数
 * @return: undefined
 * @description: 调用wx.redirectTo进行重定向，并将参数进行格式化，拼接在地址后
 */
const redirectTo = (params, data) => {
    if (!params.url) {
        showToast({ title: 'url不能为空', duration: 1000 })
    } else {
        if (params.url.lastIndexOf('?') === params.url.length - 1) { //倘若地址以"?"结尾则将"?"去掉
            params.url = params.url.slice(0, -1)
        }
        if (data) {
            let dataKeys = Object.keys(data);
            if (params.url.indexOf('?') !== -1) { //地址中已存在参数
                dataKeys.map(item => {
                    params.url += `&${item}=${data[item]}`
                })
            } else {
                dataKeys.map((item, index) => { //地址中未存在参数
                    if (index === 0) {
                        params.url += `?${item}=${data[item]}`
                    } else {
                        params.url += `&${item}=${data[item]}`
                    }
                })
            }
        }
        wx.redirectTo(params)
    }
};

/**
 * @author Dom
 * @return: prevRoute, 跳转之前的路由。
 * @description: 用于onHide函数中, 保存调转之前的路由。
*/
const setPrevRouteToGlobal = () => {
    const pages = getCurrentPages();
    const prevRoute = pages[pages.length - 1].route;
    const globalData = getApp().globalData;
    globalData.prevRoute = prevRoute;
    console.log(globalData);
    console.log(prevRoute);
    return prevRoute;
};

/**
 * @author Dom
 * @return: prevRoute, 跳转之前的路由。
 * @description: 用于onHide函数中, 保存调转之前的路由。
 */
const getPrevRouteToGlobal = () => {
    return getApp().globalData.prevRoute;
};

/**
 * @author Dom
 * @param params, type: object
 * state: keys: title、icon、image、duration、mask
 * @param isEmptyRequestList, type: boolean
 * state: 用于控制hideLoading, 防止hideLoading操作把toast隐藏（因为两个组件, 好像是属于同一个实例）。
 * @return: undefined
 */
const showToast = (params, isEmptyRequestList = true) => {
    if (isEmptyRequestList) {
        requestList.splice(0, requestList.length)
    }
    if(typeof params === 'string') params = { title: params };
    params = Object.assign({}, { icon: 'none', mask: true, duration: 1000 }, params); //默认没有图标和遮罩
    wx.showToast(params)
};

/**
 * @author Dom
 * @param params, type: object
 * @return: undefined
 */
const hideToast = params => {
    wx.hideToast(params)
};

/**
 * @author Dom
 * @param params, type: object
 * state: keys: title、mask
 * @return: undefined
 */
const showLoading = params => {
    params = Object.assign({}, { mask: true, title: 'loading...' }, params);
    wx.showLoading(params)
};

/**
 * @author Dom
 * @param params, type: object
 * @return: undefined
 */
const hideLoading = params => {
    wx.hideLoading(params)
};

/**
 * @author Dom
 * @param params, type: object
 * state: keys: key、data
 * @return: undefined
 */
const setStorage = params => {
    wx.setStorage(params)
};

const setStorageSync = (key, value) => {
    wx.setStorageSync(key, value);
};

/**
 * @author Dom
 * @param params, type: object
 * state: keys: key
 * @return: undefined
 */
const getStorage = params => {
    wx.getStorage(params)
};

const getStorageSync = key => {
    return wx.getStorageSync(key)
};

/**
 * @author Dom
 * @param params, type: object
 * @description: 小程序之间互相跳转
*/
const navigateToMiniProgram = params => {
    wx.navigateToMiniProgram(params)
}

/**
 * @author Dom
 * @param value, type: string
 * state: developPerson, 发展人标识
 * @return: value, 发展人标识
 * @description: 将发展人标识保存到本地缓存中, 同步操作, 不能配置success、fail、complete等callback。
 */
const setDevelopPerson = value => {
    if (typeof value === 'object' && value.developPerson) {
        value = value.developPerson;
    }
    wx.setStorageSync('developPerson', value);
    return value
};

/**
 * @author Dom
 * @return: developPerson, 发展人标识
 * @description: 从本地缓存中获取发展人标识, 同步操作, 不能配置success、fail、complete等callback。
 */
const getDevelopPerson = () => {
    return wx.getStorageSync('developPerson')
};

/**
 * @author chay
 * @params： int
 * @return: 3708.25
 * @description: 分转  元
 */
const to2yuan = (params) => {
    let num = params;
    num = num * 0.01;//分到元
    num += '';//转成字符串
    let reg = num.indexOf('.') > -1 ? /(\d{1,3})(?=(?:\d{3})+\.)/g : /(\d{1,3})(?=(?:\d{3})+$)/g;//千分符的正则
    return num.replace(reg, '$1');
};

/**
 * @author chay
 * @modify: Dom
 * @params： 时间戳
 * @return: 2018-9-26 14:22
 * @description: 时间戳 转 2018-9-26 14:22
 */
const formatDateTime = (params) => {
    let date = params ? new Date(params) : new Date();
    let y = date.getFullYear();
    let m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    let d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    let h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    let minute = date.getMinutes();
    let second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return y + '/' + m + '/' + d + ' ' + h + ':' + minute + ':' + second;
};

/**
 * @author remele
 * @return: obj
 * @description: 获取页面携带的参数
 */
const getFragment = () => {
    let pages = getCurrentPages();
    return pages[pages.length - 1].options
};

module.exports = {
    navigateTo,
    navigateBack,
    redirectTo,
    setPrevRouteToGlobal,
    getPrevRouteToGlobal,
    showToast,
    hideToast,
    showLoading,
    hideLoading,
    setStorage,
    setStorageSync,
    getStorage,
    getStorageSync,
    navigateToMiniProgram,
    setDevelopPerson,
    getDevelopPerson,
    to2yuan,
    formatDateTime,
    getFragment
};